# -*- coding: UTF-8 -*-
"""
Course:        CS408 Computer Science Project B, TEAM 1
Semester:      2010 SPRING
Project:       DOHN(Web-based Account Book System)

File:          shortcuts.py
Description:   Shortcut package for shortcut view.
Class:         ShortcutView, ShortcutController, Shortcut
"""


import os
import string

import sessions
import db
import utils
import views
import transactions


def __reassemble_items__(data, start = 0, end = 0, keyword = ""):
    """
    @author: Kyeonghwan Jin
    
    
    category, description, amount, plan_remain, plan_total, num
    
                <tr>
                    <td>Category1</td>
                    <td>Description1</td>
                    <td>Amount1</td>
                    <td>count1 / count2</td>
                    <td>Edit</td>
                    <td>Del</td>
                </tr>
                
    """
    check_range = not(0 == start and 0 == end)
    check_keyword = not("" == keyword)
    
    balance = 0.0
    tr_list = "\t\t\t<tr>\n"
    in_src = []
    for i, atuple in enumerate(data):
        in_src.append(tr_list)
        
        if check_range:
            if not(str(atuple[0])[:10] >= start and str(atuple[0])[:10] <= end):
                continue
        
        if check_keyword:
            if -1 == str(atuple).lower().find(str(keyword).lower()):
                continue
        
        for j, value in enumerate(atuple):
            aitem = str(value).strip()
            #Category1
            #Description1
            #Amount1
            #count1 / count2
            #Edit
            #Del
            
            
            #Category1
            if 0 == j:
                aitem = utils.get_category_name(aitem)
                aitem = aitem
                
            #Description1
            elif 1 == j:
                aitem = aitem
                
            # Amount1
            elif 2 == j:
                aitem = aitem
                
            # count1
            elif 3 == j:
                previous = aitem
                continue
            # count1 / count2
            elif 4 == j:
                aitem = previous + "/" + aitem 
                
            #Num
            elif 5 == j:
                # Edit, Del Button
                del_src = "\t\t\t\t<td>" + \
                          "<a href=\"do_shortcut_delete?num=%s\">" % (aitem) + \
                          "Del</a></td>\n"
                edit_src = "\t\t\t\t<td>" + \
                           "<a href='javascript:open_window(\"shortcut_edit?num=%s\")'>Edit</a>\n" % (aitem)
                in_src.append(edit_src)
                in_src.append(del_src)
                break
            
            in_src.append("\t\t\t\t<td>%s</td>\n" % (aitem))
            
        #End for j
        in_src.append("\t\t\t</tr>\n")
    #End for i
    in_src = ''.join(in_src)
    if 1 >= len(in_src):
        in_src = str(in_src)
    return in_src


class ShortcutView:
    
    def show_index_window(self, req):
        """
        @author: Kyeonghwan Jin
        """
        return self.show_list_window(req)
        #proper return?
    
    def show_list_window(self, req, start = 0, end = 0, keyword = ""):
        """
        @author: Kyeonghwan Jin
        """
        # @@Information
        # 1. Columns of shortcut_tb
        # num  user_id  date  description  amount  category  from  deleted
            #need to check out the shortcut table
        # 2. HTML tags of each transaction
        
        
        # ----------------------------------------
        # Fetch shortcut list
        session_id = sessions.get_id(req)
        query = "SELECT category, description, amount, plan_remain, plan_total, num " + \
                "FROM shortcut_tb " + \
                "WHERE( user_id = '%s' )" % (session_id)
        data = db.run_query(query)
        
        # Reassemble items ----------------------------------------
        # @see: I use not string concatenation but list join for speed up.
        if 0 == start and 0 == end and "" == keyword:
            in_src = __reassemble_items__(data)
        elif not "" == keyword:
            in_src = __reassemble_items__(data, 0, 0, keyword)
        else:
            in_src = __reassemble_items__(data, start, end)
            
        # Get HTML and replace ----------------------------------------
        #src = utils.replace(src, "<!---TRX!--->", in_src)
        #src = utils.replace("transaction.html", in_src)
        src_path = src_path = utils.get_abs_path() + "/html/shortcut.html"
        src = utils.get_file_content(src_path)
        src = src.replace("ShortcutTopTitle", "TitleTest")
        src = src.replace("<!---CONTENT!--->", in_src)
        return src
        
        
    def show_add_window(self, req):
        """
        @author: Kyeonghwan Jin
        """
        session_id = sessions.get_id(req)
        query = "SELECT num, description FROM category_tb " + \
                "WHERE(user_id = '%s') ORDER BY `order`" % (session_id)
        data = db.run_query(query)
        
        # Category
        in_src = str(utils.get_category_dropdown_src(session_id))
        
        src_path = utils.get_abs_path() + "/html/p_add_shortcut.html"
        src = str(utils.get_file_content(src_path))
        src = src.replace("<!---CONTENT!--->", in_src)
        return src
    
    
    def show_edit_window(self, req, num):
        """
        @author: Kyeonghwan Jin
        """
        # Fetch transaction data ----------------------------------------
        session_id = sessions.get_id(req)
        query = "SELECT category, description, amount, plan_remain, plan_total, user_id " + \
                "FROM shortcut_tb WHERE(num='%s')" % (num)
        data = db.run_query(query)
        if 0 == len(data):
            return "There is no transaction data on num=%s." % (num)
        
        # Check permission ----------------------------------------
        if not data[0][5] == sessions.get_id(req):
            return "You don't have permission to edit this transaction."
        
        # Unpack tuple of transaction ----------------------------------------
        cate, desc, amnt, plan_remain, plan_total, user_id = data[0]
        cate_name = str(utils.get_category_name(cate))
        count = str(plan_remain) + "/" + str(plan_total)
        
        # Make category data ----------------------------------------
        in_src = str(utils.get_category_dropdown_src_with_selected(session_id, cate))
            
        # Make hidden input box for num ----------------------------------------
        hidden_input = "<input type=\"hidden\" name=\"num\" " + \
                       "value=\"%s\" />" % (num)
        
        # Get HTML and replace ----------------------------------------
        src_path = utils.get_abs_path() + "/html/p_edit_shortcut.html"
        src = str(utils.get_file_content(src_path))
        
        src = src.replace("Content_cate", str(cate))
        src = src.replace("Content_Category", cate_name)
        src = src.replace("Content_Description", desc)
        src = src.replace("Content_Amount", str(amnt))
        src = src.replace("Content_Count", count)
        src = src.replace("Content_Plan_Remain", str(plan_remain))
        src = src.replace("Content_Plan_Total", str(plan_total))
        src = src.replace("<!---CONTENT!--->", in_src)
        src = src.replace("<!---HIDDEN!--->", hidden_input);
        return src
    

class ShortcutController:
    def query_add_shortcut(self, req, description, amount, category, plan_remain, plan_total):
        """
        @author: Kyeonghwan Jin
        """
        # @@Information
        # 1. Columns of shortcut_tb
        # num  user_id  date  description  amount  category  from  deleted
            #need to check out the shortcut table
        user_id = sessions.get_id(req)
        if not utils.is_number(category):
            category = utils.get_category_num(user_id, category)

        query = "INSERT INTO shortcut_tb (`num`, `user_id`, `description`, " + \
                "`amount`, `category`, `order`, `plan_remain`, `plan_total`) VALUES " + \
                "(NULL, '%s', '%s', '%+15.2f', '%s', '0', '%s', '%s')" \
                %(user_id, description, float(amount), int(category), int(plan_remain), int(plan_total))
        db.execute_query(query)
        
        # pattern_tb
        query = "SELECT num FROM pattern_tb WHERE (user_id='%s' AND category='%d' " % (user_id, int(category)) + \
                "AND description='%s')" % (description)
        data = db.run_query(query)
        if len(list(data)) == 0:
            query = "INSERT INTO pattern_tb (user_id, category, description) " + \
                    "VALUES('%s', '%s', '%s')" % (user_id, category, description)
        db.execute_query(query)
        
        return
    
    def query_edit_shortcut(self, req, num, description, amount, category, plan_remain, plan_total):
        """
        @author: Kyeonghwan Jin
        """
        # example query for transaction
        """
        UPDATE `dohn`.`transaction_tb` SET `description` = 'trx2 description!' 
        WHERE `transaction_tb`.`num` =3 AND `transaction_tb`.`user_id` = 'test' AND
              `transaction_tb`.`category` =2 LIMIT 1 ;
        """
        user_id = sessions.get_id(req)
        if not utils.is_number(category):
            category = utils.get_category_num(user_id, category)
                    
        # past data
        query = "SELECT description, category FROM shortcut_tb " + \
                "WHERE( user_id='%s' AND num='%s')" % (user_id, num)
        data = db.run_query(query)  #: (('trx1', 0L),)
        past_description = str(data[0][0]).strip()
        past_category = str(data[0][1]).strip()
        
        # shortcut_tb
        query = "UPDATE shortcut_tb SET " + \
                "`description` = '%s', " % (description) + \
                "`amount` = '%+15.2f', " % (float(amount)) + \
                "`category` = '%s', " % (category) + \
                "`plan_remain` = '%s', " % (int(plan_remain)) + \
                "`plan_total` = '%s' " % (int(plan_total)) + \
                "WHERE(`user_id`='%s' AND `num` = '%s') LIMIT 1" % (user_id, num)
        db.execute_query(query)
        
        # pattern_tb
        query = "SELECT num FROM pattern_tb WHERE (user_id='%s' AND category='%d' " % (user_id, int(category)) + \
                "AND description='%s')" % (description)
        data = db.run_query(query)
        if len(list(data)) == 0:
            query = "UPDATE pattern_tb SET category = '%s', " % (category) + \
                "description = '%s' " % (description) + \
                "WHERE(user_id='%s' AND description='%s' AND category='%s')" \
                % (user_id, past_description, past_category)
            db.execute_query(query)
        return
    
    def query_delete_shortcut(self, req, num):
        """
        @author: Kyeonghwan Jin
        """
        user_id = sessions.get_id(req)
                
        # past data --------------------
        query = "SELECT description FROM shortcut_tb " + \
                "WHERE(user_id='%s' AND num='%s')" % (user_id, num)
        data = db.run_query(query)
        past_description = str(data[0][0]).strip()
        
        # shortcut_tb
        """
        query = "UPDATE shortcut_tb SET deleted = '1' " + \
                "WHERE(user_id='%s' AND num = '%s') LIMIT 1" % (user_id, num)
        """
        query = "DELETE from shortcut_tb WHERE (user_id='%s' AND num = '%s') LIMIT 1" % (user_id, num)
        db.execute_query(query)
        
        # pattern_tb --------------------
        query = "DELETE FROM pattern_tb WHERE(user_id='%s' " % (user_id) + \
                "AND description='%s') LIMIT 1" % (past_description)
        db.execute_query(query)
        return True
        
class Shortcut:

    def __init__(self, description = "", amount = 0.0, plan_remain = 0, plan_total = 0, category = 1):
        """
        @author: Kyeonghwan Jin
        """
        self.description = description
        self.amount = amount
        self.plan_remain = plan_remain
        self.plan_total = plan_total
        self.category = category

